using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using _03.作用域与对象释放行为_IDisposable对象释放的时机.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace _03.作用域与对象释放行为_IDisposable对象释放的时机
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }


        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddTransient<IOrderService, DisposableOrderService>();

            //services.AddScoped<IOrderService>(p=>new DisposableOrderService());

            //services.AddSingleton<IOrderService>(p=>new DisposableOrderService());

            //避免手动创建实现了IDisposable对象,应该使用容器来管理其生命周期
            //自己创建对象放入到容器,容器是不会帮我们去管理对象的生命周期
            //var service = new DisposableOrderService();
            //services.AddSingleton<IOrderService>(service);

            //services.AddSingleton<IOrderService, DisposableOrderService>();

            services.AddTransient<IOrderService, DisposableOrderService>();

            services.AddControllers();
        }


        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //坑1:避免在根容器获取实现了IDisposable接口的瞬时服务
            //实现了IDisposable接口的服务,如果是瞬时的,在根容器去获取对象,对象会一直保持到应用程序退出的时候才能够被回收
            //从根容器获取瞬时服务
            var s1 = app.ApplicationServices.GetService<IOrderService>();
            var s2 = app.ApplicationServices.GetService<IOrderService>();
            var s3 = app.ApplicationServices.GetService<IOrderService>();
            var s4 = app.ApplicationServices.GetService<IOrderService>();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
